import { createElement, HTMLAttributes, useState, type FC } from 'react';
import classNames from 'classnames';

import { embedDefaultProps } from './defaultProps';
import type { EmbedOptions } from './type';

export interface EmbedProps extends EmbedOptions, HTMLAttributes<HTMLDivElement> {}

const Embed: FC<EmbedProps> = (props) => {
  const { className, ui, placeholder, icon, url, ratio, forwardedRef, ...embedProps } = props;
  const [active, setActive] = useState(false);

  const handleClick = () => {
    setActive(true);
  };

  return createElement(
    'div',
    {
      ref: forwardedRef,
      className: classNames({ ui }, ratio, 'embed', { active }, className),
      onClick: handleClick,
      ...embedProps,
    },
    [
      <i key="icon" className={`${icon} icon`}></i>,
      <img key="placeholder" className="placeholder" src={placeholder} alt="placeholder" />,
      active && (
        <div key="embed" className="embed">
          <iframe src={url} referrerPolicy="unsafe-url" width="100%" height="100%" allowFullScreen></iframe>
        </div>
      ),
    ],
  );
};

Embed.displayName = 'Embed';
Embed.defaultProps = embedDefaultProps;

export default Embed;
